package com.itlong.cloud.utils.encrypt;

import com.itlong.cloud.PlatformConstants;
import com.itlong.cloud.enumerate.SystemTypeEnum;
import com.sun.org.apache.xerces.internal.impl.dv.util.Base64;
import org.slf4j.Logger;import org.slf4j.LoggerFactory;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

/**
 * <desc>
 *      用户token加解密帮助类
 * </desc>
 *
 * @createDate 2017/09/15
 */
public class UserTokenUtil {
    private static final Logger LOG = LoggerFactory.getLogger(UserTokenUtil.class);
    /**
     * <desc>
     *      token加密   加密顺序urlEncode > des > base64
     *      加密规则 用户key前缀+用户id 进行des加密
     * </desc>
     *
     * @param userKey 用户id
     * @desKey des加密key
     * @return token
     * @author Jiaqi.X
     * @createDate 2017/09/15
     */
    public static String tokenEncrypt(String userKey,String desKey,Integer type) throws UnsupportedEncodingException {
        if(SystemTypeEnum.OPERATE.getType().equals(type)){
            //运营
            userKey= PlatformConstants.OPERATE_USER_TOKEN_PREFIX+userKey;
        }else if(SystemTypeEnum.PROPERTY.getType().equals((type))){
            //物业
            userKey= PlatformConstants.PROPERTY_USER_TOKEN_PREFIX+userKey;
        }else if(SystemTypeEnum.IOS.getType().equals((type))){
            //APP
            userKey = PlatformConstants.APP_USER_TOKEN_PREFIX+userKey;
        }else if(SystemTypeEnum.SDK_SERVER.getType().equals((type))){
            //SDK服务端
            userKey = PlatformConstants.APP_USER_TOKEN_PREFIX+userKey;
        }else if (SystemTypeEnum.CLOUD_TALK_SERVER.getType().equals(type)){
            //云对讲设备服务端
            userKey = PlatformConstants.CLOUD_TALK_TOKEN_PREFIX + userKey;
        }  else if (SystemTypeEnum.SMART_CARD.getType().equals(type)){
            //一卡通
            userKey = PlatformConstants.SMART_CARD_TOKEN_PREFIX + userKey;
        }  else if(SystemTypeEnum.CLOUD_ELEVATOR_SERVER.getType().equals(type)){
            //云电梯设备端
            userKey = PlatformConstants.CLOUD_ELEVATOR_TOKEN_PREFIX + userKey;
        }  else if(SystemTypeEnum.CLOUD_ELEVATOR_SERVER.getType().equals(type)){
            //云门禁设备端
            userKey = PlatformConstants.CLOUD_ENTRANCE_TOKEN_PREFIX + userKey;
        }else if(SystemTypeEnum.CLOUD_TALK_SDK_SERVER.getType().equals(type)){
            //云对讲SDK
            userKey = PlatformConstants.CLOUDTALK_SDK_USER_TOKEN_PREFIX + userKey;
        } else if (SystemTypeEnum.ROBOT.getType().equals(type)) {
            // 机器人
            userKey = PlatformConstants.ROBOT_USER_TOKEN_PREFIX + userKey;
        }else if (SystemTypeEnum.MINI_PROGRAM.getType().equals(type)) {
            // 微信小程序
            userKey = PlatformConstants.MINI_PROGRAM_USER_TOKEN_PREFIX + userKey;
        }else if (SystemTypeEnum.PROPERTY_APP.getType().equals(type)){
            userKey = PlatformConstants.PROPERTY_APP_USER_TOKEN_PREFIX + userKey;
        }
        return Base64.encode(DesEncryptUtil.Encrypt(URLEncoder.encode(new String(userKey.getBytes()), "utf-8").getBytes(), desKey));
    }

    /**
     * <desc>
     *      token解密
     * </desc>
     * @param token
     * @param desKey
     * @return 用户id
     * @author Jiaqi.X
     * @createDate 2017/09/15
     */
    public static String tokenDecrypt(String token,String desKey){
        String decryStr = null;
        try {
            byte[] decryResult = DesEncryptUtil.Decrypt(Base64.decode(token), desKey);
            decryStr=new String(decryResult);
        }catch(IllegalArgumentException e){
            //LOG.error("【获取用户token解密出用户ID】token错误", e);
        } catch (Exception e) {
            LOG.info("【获取用户token解密出用户ID】DES解密失败", e);
        }
        String[] keys = decryStr!=null ? decryStr.split("_") : new String[]{};
        return keys.length > 1 ? keys[keys.length-1] : null;
    }

    /**
     * <desc>
     *      APP2.0新版token解密,在原有基础上添加了日期
     * </desc>
     * @param token
     * @param desKey
     * @return 用户id
     * @author Jiaqi.X
     * @createDate 2017/09/15
     */
    public static String newAPPTokenDecrypt(String token,String desKey){
        String decryStr = null;
        try {
            byte[] decryResult = DesEncryptUtil.Decrypt(Base64.decode(token), desKey);
            decryStr=new String(decryResult);
        }catch(IllegalArgumentException e){
            //LOG.error("【获取用户token解密出用户ID】token错误", e);
        } catch (Exception e) {
            LOG.info("【获取用户token解密出用户ID】DES解密失败", e);
        }
        String[] keys = decryStr!=null ? decryStr.split("_") : new String[]{};
        String userId = keys.length > 1 ? keys[keys.length-1] : null;
        if (userId.length() != 11 && userId.length() != 32 && userId.length() != 18) {
            userId = userId.substring(0,userId.length()-10);
        }
        return userId;
    }

    /**
     * <desc>
     *      用户登录密码解密
     * </desc>
     * @param token
     * @param desKey
     * @return 用户id
     * @author Jiaqi.X
     * @createDate 2018/05/02
     */
    public static String tokenDecrypt1(String token,String desKey){
        String decryStr = null;
        try {
            byte[] decryResult = DesEncryptUtil.Decrypt(Base64.decode(token),desKey);
            decryStr=new String(decryResult);
        }catch(IllegalArgumentException e){
              //token格式错误，可以忽略
              //LOG.error("【获取用户token解密出用户ID】token错误", e);
        } catch (Exception e) {
            LOG.info("【获取用户token解密出用户ID】DES解密失败", e);
        }

        return decryStr;
    }

    /**
     * <desc>
     *      用户登录密码解密调用
     * </desc>
     * @param passwords
     * @return 解密后的密码
     * @author Juguang.S
     * @createDate 2018/05/03
     */
    public static String getPassword(String passwords,String key){
        return tokenDecrypt1(passwords,key);
    }


    /**
     * <desc>
     *      物业系统单点登录——token解密
     * </desc>
     * @param token
     * @param desKey
     * @return 用户id
     * @author Juguang.S
     * @createDate 2018/05/02
     */
    public static String tokenDecryptBySSO(String token,String desKey){
        String decryStr = null;
        try {
            byte[] decryResult = DesEncryptUtil.Decrypt(Base64.decode(token), desKey);
            decryStr=new String(decryResult);
            int i = decryStr.lastIndexOf("_");
            decryStr=decryStr.substring(0,i);
        }catch(IllegalArgumentException e){
            //LOG.error("【获取用户token解密出用户ID】token错误", e);
        } catch (Exception e) {
            LOG.info("【获取用户token解密出用户ID】DES解密失败", e);
        }
        String[] keys = decryStr!=null ? decryStr.split("_") : new String[]{};
        return keys.length > 1 ? keys[keys.length-1] : null;
    }

    /**
     * <desc>
     *      文件密码解密
     * </desc>
     * @param token
     * @param desKey
     * @return 用户id
     * @author Juguang.S
     * @createDate 2020/08/17
     */
    public static String authFilePsdDecrypt(String token,String desKey){
        String decryStr = null;
        try {
            byte[] decryResult = DesEncryptUtil.Decrypt(Base64.decode(token), desKey);
            decryStr=new String(decryResult);
        }catch(IllegalArgumentException e){
            //LOG.error("【获取用户token解密出用户ID】token错误", e);
        } catch (Exception e) {
            LOG.info("【获取用户token解密出用户ID】DES解密失败", e);
        }
        return decryStr;
    }

//    public static void main(String[] args) throws Exception{
//        String str = Base64.encode(DesEncryptUtil.Encrypt(URLEncoder.encode(new String("song".getBytes()), "utf-8").getBytes(), "88BE65278OPP54123658BAC74166BE"));
//        System.out.println("加密--"+str);
//        String aa = UserTokenUtil.tokenDecrypt(str,"88BE65278OPP54123658BAC74166BE");
//        System.out.println("解密--"+aa);
//    }



}
